<template>
  <div class="personal-center-container">
    <el-row :gutter="20">
      <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24">
        <vab-card shadow="hover">
          <div class="personal-center-user-info">
            <el-avatar :size="100" :src="avatar" @click="openDialog" />
            <div class="personal-center-user-info-full-name">
              {{ form.fullName }}
            </div>
            <div class="personal-center-user-info-description">
              {{ form.description }}
            </div>

            <ul class="personal-center-user-info-list">
              <li>
                <vab-icon icon="user-3-line" />
                员工
              </li>
              <li>
                <vab-icon icon="community-line" />
                万花商 - 事业群 - 技术部
              </li>
              <li>
                <vab-icon icon="map-pin-2-line" />
                中国 • 广东省 • 揭阳市
              </li>
              <li>
                <el-divider />
                <h5>个性标签</h5>
                <el-tag v-for="tag in dynamicTags" :key="tag">
                  {{ tag }}
                </el-tag>
              </li>
            </ul>
          </div>
        </vab-card>
      </el-col>
      <el-col :lg="16" :md="12" :sm="24" :xl="16" :xs="24">
        <vab-card shadow="hover">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-col :lg="12" :md="16" :sm="24" :xl="12" :xs="24">
                <el-form
                  ref="userRef"
                  label-width="80px"
                  :model="form"
                  :rules="rules"
                >
                  <el-form-item label="旧密码" prop="old_password">
                    <el-input v-model="form.old_password" type="password" />
                  </el-form-item>
                  <el-form-item label="新密码" prop="new_password">
                    <el-input v-model="form.new_password" type="password" />
                  </el-form-item>
                  <el-form-item label="确认密码" prop="confirm_password">
                    <el-input v-model="form.confirm_password" type="password" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </vab-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { useUserStore } from '@/store/modules/user'
  import { resetPassword } from '@/api/user'
  export default defineComponent({
    name: 'UserCenter',
    setup() {
      const $baseMessage = inject('$baseMessage')

      const userStore = useUserStore()
      const { avatar, username } = storeToRefs(userStore)

      const _description =
        '万花商，一个专注线上电商的平台，为电商求购者提供最新最全的商品物料信息，为商品企业采购提供最有效的解决方案。'

      // 密码验证规则
      const validatePassword = (rule, value, callback) => {
        // 密码必须包含数字和字母，且长度大于6位
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
        if (!value) {
          callback(new Error('请输入密码'))
        } else if (!passwordRegex.test(value)) {
          callback(new Error('密码必须包含数字和字母不少于8位'))
        } else {
          callback()
        }
      }

      // 确认密码验证规则
      const validateConfirmPassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'))
        } else if (value !== state.form.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }

      // 新旧密码不能相同的验证规则
      const validateNewPassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码'))
        } else if (value === state.form.old_password) {
          callback(new Error('新密码不能与旧密码相同'))
        } else {
          // 当新密码变化时，同时验证确认密码
          if (state.form.confirm_password) {
            userRef.value.validateField('confirmPassword')
          }
          callback()
        }
      }

      const state = reactive({
        vabCropperRef: null,
        activeName: 'first',
        form: {
          fullName: username,
          nickname: 'good luck',
          sex: 2,
          description: _description,
          old_password: '',
          new_password: '',
          confirm_password: '',
        },
        inputRef: null,
        dynamicTags: ['电商', '采购', '物料'],
        inputVisible: false,
        inputValue: '',
        rules: {
          old_password: [
            { required: true, message: '请输入旧密码', trigger: 'blur' },
            { validator: validatePassword, trigger: 'blur' },
          ],
          new_password: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { validator: validateNewPassword, trigger: 'blur' },
          ],
          confirm_password: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { validator: validateConfirmPassword, trigger: 'blur' },
          ],
        },
      })

      const openDialog = () => {
        state['vabCropperRef'].dialogVisible = true
      }
      const userRef = ref(null)
      const onSubmit = () => {
        userRef.value.validate((valid) => {
          if (valid) {
            ElMessageBox.confirm('确定要修改密码吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(() => {
              resetPassword(state.form).then((res) => {
                $baseMessage(
                  '修改密码成功',
                  'success',
                  'vab-hey-message-success'
                )
              })
            })
          }
        })
      }

      const handleClose = (tag) => {
        state.dynamicTags.splice(state.dynamicTags.indexOf(tag), 1)
      }

      const showInput = () => {
        state.inputVisible = true
        nextTick(() => {
          state.inputRef.focus()
        })
      }

      const handleInputConfirm = () => {
        if (state.inputValue) {
          state.dynamicTags.push(state.inputValue)
        }
        state.inputVisible = false
        state.inputValue = ''
      }

      return {
        userRef,
        ...toRefs(state),
        avatar,
        openDialog,
        onSubmit,
        showInput,
        handleClose,
        handleInputConfirm,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.personal-center';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;

    #{$base}-user-info {
      padding: $base-padding;
      text-align: center;

      :deep() {
        .el-avatar {
          img {
            cursor: pointer;
          }
        }
      }

      &-full-name {
        margin-top: 15px;
        font-size: 24px;
        font-weight: 500;
        color: #262626;
      }

      &-description {
        margin-top: 8px;
      }

      &-follow {
        margin-top: 15px;
      }

      &-list {
        margin-top: 18px;
        line-height: 30px;
        text-align: left;
        list-style: none;

        h5 {
          margin: -20px 0 5px;
        }

        :deep() {
          .el-tag {
            margin-right: 10px !important;
          }

          .el-tag + .el-tag {
            margin-left: 0;
          }
        }
      }
    }

    #{$base}-item {
      display: flex;

      i {
        font-size: 40px;
      }

      &-content {
        box-sizing: border-box;
        flex: 1;
        margin-left: $base-margin;

        &-second {
          margin-top: 8px;
        }
      }
    }
  }
</style>
